package tool

import (
	"errors"
	p "fhst/templates"
	"fhst/utils"
	"fmt"
	"strings"

	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

func AddLogger() error {
	// 判断当前位置是否有utils文件夹
	if !utils.IsPathExists(".fhst") {
		return errors.New("未发现.fhst文件，请回到项目根目录")
	}

	if utils.IsPathExists("utils/log") {
		return errors.New("utils/log文件夹已存在")
	}

	log.Infof("初始化Log目录")
	// 创建核心文件夹
	_, err := utils.ExecCommandString("mkdir -p utils/log")
	if err != nil {
		return err
	}

	rs, err := utils.ReadFile(".fhst")
	if err != nil {
		return err
	}

	pkgname := strings.Split(string(rs), ":")
	data := map[string]interface{}{
		"Pkg":         pkgname[1],
		"ProjectName": pkgname[0],
		"Log":         true,
		"Admin":       viper.GetBool("admin"),
		"Apps":        viper.GetStringSlice("app"),
		"Jwt":         viper.GetBool("jwt"),
		"Swagger":     viper.GetBool("swagger"),
	}

	// 写入配置文件
	defer func() {
		viper.Set("log.enable", true)
		viper.WriteConfigAs(fmt.Sprintf("%s.yaml", pkgname[0]))
	}()

	log.Infof("初始化log/entry.go")
	err = utils.WriteFileByTemplate(p.Tool, "tool/log/entry.tmpl", "utils/log/entry.go", nil)
	if err != nil {
		return err
	}

	log.Infof("初始化log/format.go")
	err = utils.WriteFileByTemplate(p.Tool, "tool/log/format.tmpl", "utils/log/format.go", nil)
	if err != nil {
		return err
	}

	log.Infof("初始化log/logger.go")
	err = utils.WriteFileByTemplate(p.Tool, "tool/log/logger.tmpl", "utils/log/logger.go", data)
	if err != nil {
		return err
	}

	// 创建root.go
	log.Infof("更新root.go Log配置")
	err = utils.WriteFileByTemplate(p.Project, "project/root.tmpl", "cmd/root.go", data)
	if err != nil {
		return err
	}

	return nil
}
